package com.cskaoyan.service.admin;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.admin.goods.GoodsCreateBO;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.admin.goods.GoodsCatAndBrandVO;
import com.cskaoyan.bean.vo.admin.goods.GoodsDetailVO;
import com.cskaoyan.bean.vo.wx.GoodDetailVO;
import com.cskaoyan.bean.vo.wx.GoodsDetailInnerCommentVO;
import com.cskaoyan.bean.vo.wx.GoodsDetailInnerSpecificationListVO;
import com.cskaoyan.mapper.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.cskaoyan.bean.MarketGoods.Column;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/**
 * @Description
 * @Author klw
 * @Data 2022/11/19 下午3:19
 */

@Service
public class GoodsServiceImpl implements GoodsService{

    Column[] columns = new Column[]{Column.id, Column.name, Column.brief, Column.picUrl, Column.isHot, Column.isNew, Column.counterPrice, Column.retailPrice};



    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCategoryMapper marketCategoryMapper;

    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;

    @Autowired
    MarketBrandMapper marketBrandMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketGrouponMapper marketGrouponMapper;

    @Autowired
    MarketIssueMapper marketIssueMapper;

    @Autowired
    MarketCollectMapper marketCollectMapper;


    @Override
    public CommonData<MarketGoods> query(String goodsSn, Integer goodsId, String name, BasePageInfo info) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setDistinct(true);
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();

        if(goodsId != null && !"".equals(goodsId)){
            criteria.andIdEqualTo(goodsId);
        }
        if(goodsSn != null && !"".equals(goodsSn)){
            criteria.andGoodsSnEqualTo(goodsSn);
        }
        if(name != null && !"".equals(name)){
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(0);
        marketGoodsExample.setOrderByClause(info.getSort() + " " + info.getOrder());
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        PageInfo pageInfo = new PageInfo(marketGoods);

        return CommonData.data(pageInfo);
    }



    @Override
    public GoodsCatAndBrandVO getCatAndBrand() {
        GoodsCatAndBrandVO goodsCatAndBrandVO = new GoodsCatAndBrandVO();
        goodsCatAndBrandVO.setCategoryList(marketCategoryMapper.selectGoodsInnerCatVO());
        goodsCatAndBrandVO.setBrandList(marketCategoryMapper.selectGoodsInnerBrandVO());
        return goodsCatAndBrandVO;
    }

    @Override
    @Transactional
    public int createGoods(GoodsCreateBO goodsCreateBO) {
        String goodsSn = goodsCreateBO.getGoods().getGoodsSn();
        String name = goodsCreateBO.getGoods().getName();

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setDistinct(true);
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        MarketGoodsExample.Criteria criteria2 = marketGoodsExample.createCriteria();
        if(goodsSn != null && !"".equals(goodsSn)){
            criteria.andGoodsSnEqualTo(goodsSn);
        }else {
            return 401;
        }
        if(name != null && !"".equals(name)){
            criteria2.andNameEqualTo(name);
        }else {
            return 401;
        }
        marketGoodsExample.or(criteria2);  // 商品名或商品编号的筛选
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        if(!marketGoods.isEmpty()){
            return 611;
        }


        //正式向数据库的四个表中插入数据,并解决goodsid 和 time/deleted的问题 retail_price
        MarketGoods goods = goodsCreateBO.getGoods();
        goods.setAddTime(new Date());
        goods.setUpdateTime(new Date());
        goods.setDeleted(false);
        List<MarketGoodsProduct> products = goodsCreateBO.getProducts();
        products.sort(Comparator.comparing(MarketGoodsProduct::getPrice)); //按价格升序排列
        goods.setRetailPrice(products.get(0).getPrice());  // 搞定retail_price
        marketGoodsMapper.insert(goods);
        Integer goods_id = goodsCreateBO.getGoods().getId();

        for (MarketGoodsAttribute attribute : goodsCreateBO.getAttributes()) {
            attribute.setGoodsId(goods_id);
            attribute.setAddTime(new Date());
            attribute.setUpdateTime(new Date());
            attribute.setDeleted(false);
            marketGoodsAttributeMapper.insert(attribute);
        }
        for (MarketGoodsProduct product : goodsCreateBO.getProducts()) {
            product.setId(null);
            product.setGoodsId(goods_id);
            product.setAddTime(new Date());
            product.setUpdateTime(new Date());
            product.setDeleted(false);
            marketGoodsProductMapper.insert(product);
        }
        for (MarketGoodsSpecification specification : goodsCreateBO.getSpecifications()) {
            specification.setGoodsId(goods_id);
            specification.setAddTime(new Date());
            specification.setUpdateTime(new Date());
            specification.setDeleted(false);
            marketGoodsSpecificationMapper.insert(specification);
        }

        return 0;
    }



    @Override
    public void delete(MarketGoods marketGoods) {
        Integer id = marketGoods.getId();
        marketGoodsMapper.deleteByid(id);
    }

    @Override
    public GoodsDetailVO selectGoodDetailVOById(Integer id) {
        MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(id);
        Integer categoryid = marketGoods.getCategoryId();

        List <Integer> categoryIds = marketCategoryMapper.selectIds(categoryid);

        List<MarketGoodsAttribute> attributes = marketGoodsAttributeMapper.selectByGoodsId(id);
        List<MarketGoodsSpecification> specifications = marketGoodsSpecificationMapper.selectByGoodsId(id);
        List<MarketGoodsProduct> products = marketGoodsProductMapper.selectByGoodsId(id);

        GoodsDetailVO goodsDetailVO = new GoodsDetailVO(categoryIds,marketGoods,attributes,specifications,products);
        return goodsDetailVO;
    }

    @Override
    public int updateGoods(GoodsCreateBO goodsCreateBO) {
        String goodsSn = goodsCreateBO.getGoods().getGoodsSn();
        String name = goodsCreateBO.getGoods().getName();

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.setDistinct(true);
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        MarketGoodsExample.Criteria criteria2 = marketGoodsExample.createCriteria();
        if(goodsSn != null && !"".equals(goodsSn)){
            criteria.andGoodsSnEqualTo(goodsSn);
        }else {
            return 401;
        }
        if(name != null && !"".equals(name)){
            criteria2.andNameEqualTo(name);
        }else {
            return 401;
        }
        marketGoodsExample.or(criteria2);  // 商品名或商品编号的筛选
        List<MarketGoods> marketGoods = marketGoodsMapper.selectByExample(marketGoodsExample);
        if(!marketGoods.isEmpty() && !marketGoods.get(0).getId().equals(goodsCreateBO.getGoods().getId())){ // 非当前商品
            return 611;  //已经存在
        }


        //正式向数据库的四个表中修改数据,并解决updateTime
        MarketGoods goods = goodsCreateBO.getGoods();
        goods.setUpdateTime(new Date());
        List<MarketGoodsProduct> products = goodsCreateBO.getProducts();
        products.sort(Comparator.comparing(MarketGoodsProduct::getPrice)); //按价格升序排列
        goods.setRetailPrice(products.get(0).getPrice());  // 搞定retail_price
        marketGoodsMapper.updateByPrimaryKeySelective(goods);

        for (MarketGoodsAttribute attribute : goodsCreateBO.getAttributes()) {
            attribute.setUpdateTime(new Date());

            marketGoodsAttributeMapper.updateByPrimaryKeySelective(attribute);
        }
        for (MarketGoodsProduct product : goodsCreateBO.getProducts()) {
            product.setUpdateTime(new Date());

            marketGoodsProductMapper.updateByPrimaryKeySelective(product);
        }
        for (MarketGoodsSpecification specification : goodsCreateBO.getSpecifications()) {
            specification.setUpdateTime(new Date());

            marketGoodsSpecificationMapper.updateByPrimaryKeySelective(specification);
        }

        return 0;

    }

    @Override
    public int selectCount() {
        int count = marketGoodsMapper.selectCount();
        return count;
    }

    @Override
    public GoodDetailVO getGoodDetail(Integer id, Integer userId) {
        MarketGoods info = marketGoodsMapper.selectByPrimaryKey(id);

        List <MarketGoodsAttribute> attribute = marketGoodsAttributeMapper.selectByGoodsId(id);

        Integer brandId = info.getBrandId();
        MarketBrand brand = marketBrandMapper.selectByPrimaryKey(brandId);

        List<MarketComment> comments = marketCommentMapper.selectByGoodsId(id);
        int count = comments.size();
        GoodsDetailInnerCommentVO comment = new GoodsDetailInnerCommentVO(count,comments);

        List<MarketGroupon> groupon = marketGrouponMapper.selectAll(); //订单模块做完之后和goods结合解决

        List <MarketIssue> issue = marketIssueMapper.selectAll();

        List <MarketGoodsProduct> productList = marketGoodsProductMapper.selectByGoodsId(id);

        List <String> specificatonName = marketGoodsSpecificationMapper.selectNames(id);//不同的规格名
        List <GoodsDetailInnerSpecificationListVO> specificationList = new ArrayList<GoodsDetailInnerSpecificationListVO>();
        for (String name : specificatonName) {
            List <MarketGoodsSpecification> valueList = marketGoodsSpecificationMapper.selectByname(name,id);
            GoodsDetailInnerSpecificationListVO goodsDetailInnerSpecificationListVO = new GoodsDetailInnerSpecificationListVO(name,valueList);
            specificationList.add(goodsDetailInnerSpecificationListVO);
        }

        Integer userHasCollect = 0;
        if(userId.equals(-1)){
            userHasCollect = 0;
        }else {
            Integer res = marketCollectMapper.selectIfHasCollect(userId, id);
            if (res != 0) {
                userHasCollect = 1;
            }
        }

        GoodDetailVO goodDetailVO = new GoodDetailVO(attribute,brand,comment,groupon,info,issue,productList,true,"",specificationList,userHasCollect);

        return goodDetailVO;
    }

    @Override
    public CommonData<MarketGoods> getRelatedGoods(Integer id) {
        int limit = 6;
        int page = 1;

        PageHelper.startPage(page, limit);

        int categoryId = marketGoodsMapper.selectCatIdById(id);
        List<MarketGoods> goods = marketGoodsMapper.selectByCatId(categoryId);  //分页问题如何解决?

        List<MarketGoods> subGoods = goods.subList(0, limit);
        int total = goods.size();
        int pages = 0;
        if (total % limit == 0) {
            pages = total / limit;
        } else {
            pages = total / limit + 1;
        }

        CommonData commonData = new CommonData();
        commonData.setLimit(limit);
        commonData.setPage(page);
        commonData.setPages(pages);
        commonData.setTotal(total);
        commonData.setList(subGoods);

        return commonData;
    }

    public MarketGoods queryGoodById(int goodId) {
       return marketGoodsMapper.selectByPrimaryKey(goodId);
    }


    public List<MarketGoods> querySelective(Integer catId, Integer brandId, String keywords, Boolean isHot, Boolean isNew, Integer offset, Integer limit, String sort, String order) {
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria1 = example.or();
        MarketGoodsExample.Criteria criteria2 = example.or();

        if (!StringUtils.isEmpty(catId) && catId != 0) {
            criteria1.andCategoryIdEqualTo(catId);
            criteria2.andCategoryIdEqualTo(catId);
        }
        if (!StringUtils.isEmpty(brandId)) {
            criteria1.andBrandIdEqualTo(brandId);
            criteria2.andBrandIdEqualTo(brandId);
        }
        if (!StringUtils.isEmpty(isNew)) {
            criteria1.andIsNewEqualTo(isNew);
            criteria2.andIsNewEqualTo(isNew);
        }
        if (!StringUtils.isEmpty(isHot)) {
            criteria1.andIsHotEqualTo(isHot);
            criteria2.andIsHotEqualTo(isHot);
        }
        if (!StringUtils.isEmpty(keywords)) {
            criteria1.andKeywordsLike("%" + keywords + "%");
            criteria2.andNameLike("%" + keywords + "%");
        }
        criteria1.andIsOnSaleEqualTo(1);
        criteria2.andIsOnSaleEqualTo(1);
        criteria1.andDeletedEqualTo(0);
        criteria2.andDeletedEqualTo(0);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(offset, limit);

        return marketGoodsMapper.selectByExampleSelective(example, columns);
    }


    public List<Integer> getCatIds(Integer brandId, String keywords, Boolean isHot, Boolean isNew) {
        MarketGoodsExample example = new MarketGoodsExample();
        MarketGoodsExample.Criteria criteria1 = example.or();
        MarketGoodsExample.Criteria criteria2 = example.or();

        if (!StringUtils.isEmpty(brandId)) {
            criteria1.andBrandIdEqualTo(brandId);
            criteria2.andBrandIdEqualTo(brandId);
        }
        if (!StringUtils.isEmpty(isNew)) {
            criteria1.andIsNewEqualTo(isNew);
            criteria2.andIsNewEqualTo(isNew);
        }
        if (!StringUtils.isEmpty(isHot)) {
            criteria1.andIsHotEqualTo(isHot);
            criteria2.andIsHotEqualTo(isHot);
        }
        if (!StringUtils.isEmpty(keywords)) {
            criteria1.andKeywordsLike("%" + keywords + "%");
            criteria2.andNameLike("%" + keywords + "%");
        }
        criteria1.andIsOnSaleEqualTo(1);
        criteria2.andIsOnSaleEqualTo(1);
        criteria1.andDeletedEqualTo(0);
        criteria2.andDeletedEqualTo(0);

        List<MarketGoods> goodsList = marketGoodsMapper.selectByExampleSelective(example, Column.categoryId);
        List<Integer> cats = new ArrayList<Integer>();
        for (MarketGoods goods : goodsList) {
            cats.add(goods.getCategoryId());
        }
        return cats;
    }



}
